package com.flow.asyncflow.core.utils.mtdd;

import com.flow.asyncflow.core.entity.codegeneration.VelocityModel;
import com.flow.asyncflow.core.entity.codegeneration.VelocityRequest;
import com.flow.asyncflow.core.entity.flowChart.GoJsLinkDataEntity;
import com.flow.asyncflow.core.entity.flowChart.GoJsNodeEntity;
import com.flow.asyncflow.core.entity.mtdd.*;
import com.flow.asyncflow.core.enums.ExecuteEnum;
import com.flow.asyncflow.core.enums.NodeTypeEnum;
import com.flow.asyncflow.core.utils.codegeneration.AsyncFlowVelocity;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.EnumConstantDeclaration;
import com.github.javaparser.ast.body.EnumDeclaration;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.MemberValuePair;
import com.github.javaparser.ast.expr.NormalAnnotationExpr;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 模块树服务类
 */
public class MTDD_Service {

    /**
     * 转换成模型树
     *
     * @return 模型树
     */
    public static MTDD_Model loadFlowTreeView() {
        MTDD_Model mtDDModel = new MTDD_Model();
        Project_Model projectModel = loadFlowTreeViewV2();

        mtDDModel.setName(projectModel.getName());
        mtDDModel.setDes(projectModel.getDes());
        mtDDModel.setProject_domainURL(projectModel.getProject_domainURL());
        mtDDModel.setProject_uk(projectModel.getProject_uk());
        mtDDModel.setProject_gitURL(projectModel.getProject_gitURL());

        for (ParentModule_Model parentModuleModel : projectModel.getParentModule_modelList()) {
            MTDD_Model.SubModule_Model subParentModuleModel = new MTDD_Model.SubModule_Model();
            subParentModuleModel.setName(parentModuleModel.getName());
            subParentModuleModel.setDes(parentModuleModel.getDes());
            subParentModuleModel.setType(2);
            subParentModuleModel.setSort(parentModuleModel.getSort());
            mtDDModel.getSubModule_modelList().add(subParentModuleModel);

            if (parentModuleModel.getModule_modelList() != null) {
                for (Module_Model moduleModel : parentModuleModel.getModule_modelList()) {
                    MTDD_Model.SubModule_Model subModuleModel = new MTDD_Model.SubModule_Model();
                    subModuleModel.setName(moduleModel.getName());
                    subModuleModel.setDes(moduleModel.getDes());
                    subModuleModel.setFilePath(moduleModel.getFilePath());
                    subModuleModel.setType(3);
                    subParentModuleModel.getSubModule_modelList().add(subModuleModel);

                    for (Operator_Model operatorModel : moduleModel.getOperator_modelList()) {
                        if (operatorModel.getName().equals("Default") || operatorModel.getName().equals("Defaults") || operatorModel.getDes().equals("默认")) {
                            continue;
                        }
                        MTDD_Model.SubModule_Model subOperatorModel = new MTDD_Model.SubModule_Model();
                        subOperatorModel.setName(operatorModel.getName());
                        subOperatorModel.setDes(operatorModel.getDes());
                        subOperatorModel.setFilePath(operatorModel.getFilePath());
                        subOperatorModel.setType(4);
                        subModuleModel.getSubModule_modelList().add(subOperatorModel);
                    }
                }
            }

        }
        List<MTDD_Model.SubModule_Model> sortList = mtDDModel.getSubModule_modelList().stream().sorted(Comparator.comparing(MTDD_Model.SubModule_Model::getSort))
                .collect(Collectors.toList());
        mtDDModel.setSubModule_modelList(sortList);

        return mtDDModel;
    }


    //region 异步流站点视图

    /**
     * 加载异步流树形视图
     *
     * @return 项目视图JSON
     */
    public static Project_Model loadFlowTreeViewV2() {
        Project_Model projectModel = new Project_Model();
        Yaml yaml = new Yaml();
        InputStream resourceAsStream = AsyncFlowVelocity.class.getClassLoader().getResourceAsStream("asyncflow.yml");
        Map<String, Object> ymlObject = yaml.load(resourceAsStream);


        loadTreeProjectInfo(projectModel, ymlObject);
        String executePackagePath = ymlObject.getOrDefault("AsyncFlowExecutePackagePath", "").toString();
        loadTreeModels(projectModel, executePackagePath);
        return projectModel;
    }

    /**
     * 加载异步流树形视图
     *
     * @param projectModel 项目模型
     * @param ymlObject    yml对象
     */
    @SneakyThrows
    private static void loadTreeProjectInfo(Project_Model projectModel, Map<String, Object> ymlObject) {
        if (ymlObject != null) {
            String uk = ymlObject.getOrDefault("appUK", "").toString();
            projectModel.setProject_uk(uk);
            String des = ymlObject.getOrDefault("projectDes", "").toString();
            projectModel.setDes(des);
            String name = ymlObject.getOrDefault("projectName", "").toString();
            projectModel.setName(name);
            String domainURL = ymlObject.getOrDefault("domainURL", "").toString();
            projectModel.setProject_domainURL(domainURL);
            String gitURL = ymlObject.getOrDefault("gitURL", "").toString();
            projectModel.setProject_gitURL(gitURL);

            //获取模块信息
            String basePackagePath = (String) ymlObject.get("AsyncFlowDomainPackagePath");
            String packagePath = basePackagePath + ".operatorenum";
            projectModel.setParentModule_modelList(new ArrayList<>());
            Class<?> clazz = AsyncFlowVelocity.getClass(packagePath, "ModuleInfoEnum");
            if (clazz == null) {
                return;
            }
            LinkedList<VelocityModel.AsyncFlowOperatorEnumInfo> asyncFlowOperatorEnumInfoList = AsyncFlowVelocity.getEnumInfo(null, (Class<Enum<?>>) clazz);
            for (VelocityModel.AsyncFlowOperatorEnumInfo c : asyncFlowOperatorEnumInfoList) {

                if ("Default".equals(c.getName()) || "默认".equals(c.getMsg())) {
                    continue;
                }
                ParentModule_Model parentModuleModel = new ParentModule_Model();
                parentModuleModel.setName((String) c.getName());
                parentModuleModel.setDes((String) c.getMsg());
                parentModuleModel.setSort((int) c.getCode());
                parentModuleModel.setFilePath(c.getOperatorEnumFilePath());
                projectModel.getParentModule_modelList().add(parentModuleModel);
            }

        } else {
            projectModel = null;
        }
    }

    /**
     * 加载异步流树形视图
     *
     * @param projectModel       项目模型
     * @param executePackagePath 路径
     */
    @SneakyThrows
    private static void loadTreeModels(Project_Model projectModel, String executePackagePath) {
        if (projectModel == null) {
            return;
        }
        if (StringUtils.isBlank(executePackagePath)) {
            return;
        }
        LinkedList<VelocityModel.AsyncFlowNodeInfo> allManagers = AsyncFlowVelocity.loadNodeAndManagerV2();
        List<VelocityModel.AsyncFlowNodeInfo> managerList = allManagers.stream().filter(c -> c.getExecuteEnum().equals(ExecuteEnum.Manager)).collect(Collectors.toList());

        Map<String, List<VelocityModel.AsyncFlowNodeInfo>> managerMap = managerList.stream().collect(Collectors.groupingBy(VelocityModel.AsyncFlowNodeInfo::getParentModuleName));
        for (Map.Entry<String, List<VelocityModel.AsyncFlowNodeInfo>> entry : managerMap.entrySet()) {
            ParentModule_Model parentModule = projectModel.getParentModule_modelList().stream().filter(c -> c.getName().equals(getModuleNameCode(entry.getKey()))).findFirst().orElse(null);
            if (parentModule == null) {
                parentModule = projectModel.getParentModule_modelList().stream().filter(c -> c.getName().equals("Default") || c.getName().equals("DefaultParentModule")).findFirst().orElse(null);
            }
            if (parentModule == null) {
                parentModule = new ParentModule_Model();
                parentModule.setName("DefaultParentModule");
                parentModule.setDes("默认");
                parentModule.setSort(1);
                projectModel.getParentModule_modelList().add(parentModule);
            }
            for (VelocityModel.AsyncFlowNodeInfo manager : entry.getValue()) {
                Module_Model moduleModel = new Module_Model();
                moduleModel.setFilePath(manager.getAsyncFlowNodeFilePath());
                moduleModel.setName(manager.getAsyncFlowNodeFileName());
                moduleModel.setDes(manager.getAsyncFlowNodeDes());
                parentModule.getModule_modelList().add(moduleModel);
                moduleModel.setOperator_modelList(new ArrayList<>());
                //加载管理器下所有节点
                VelocityRequest velocityRequest = AsyncFlowVelocity.loadManagerNode(manager.getAsyncFlowNodeFileName());
                List<VelocityModel.AsyncFlowOperatorEnumInfo> asyncFlowOperatorEnumInfoList = velocityRequest.getAsyncFlowOperatorEnumInfoList();
                List<VelocityModel.AsyncFlowNodeInfo> asyncFlowNodeInfoList = velocityRequest.getAsyncFlowNodeInfoList();
                if (!asyncFlowOperatorEnumInfoList.isEmpty()) {
                    for (VelocityModel.AsyncFlowOperatorEnumInfo asyncFlowOperatorEnumInfo : asyncFlowOperatorEnumInfoList) {
                        Operator_Model operatorModel = new Operator_Model();
                        operatorModel.setName((String) asyncFlowOperatorEnumInfo.getName());
                        operatorModel.setDes((String) asyncFlowOperatorEnumInfo.getMsg());
                        operatorModel.setFilePath(asyncFlowOperatorEnumInfo.getOperatorEnumFilePath());
                        moduleModel.getOperator_modelList().add(operatorModel);
                        operatorModel.setNode_ModelList(new ArrayList<>());
                        for (VelocityModel.AsyncFlowNodeInfo asyncFlowNodeInfo : asyncFlowNodeInfoList) {
                            Node_Model node = new Node_Model();
                            node.setName(asyncFlowNodeInfo.getAsyncFlowNodeFileName());
                            node.setDes(asyncFlowNodeInfo.getAsyncFlowNodeDes());
                            operatorModel.getNode_ModelList().add(node);

                        }
                    }
                }
            }

        }
    }

    private static String getModuleNameCode(String managerModuleDes) {

        if (managerModuleDes.contains("[") && managerModuleDes.contains("]")) {
            return managerModuleDes.split("\\[")[1].replace("]", "");
        } else {
            return managerModuleDes;
        }
    }

    /**
     * 加载节点集合
     *
     * @param managerName  模块名称
     * @param operatorName 操作节点名称
     * @return 节点集合
     */
    public static List<GoJsNodeEntity> getAllNodes(String managerName, String operatorName) {
        List<GoJsNodeEntity> asyncFlowNodeDataArrays = new ArrayList<>();

        List<Node_Model> nodeModelList = getManagerNodeInfo(managerName, operatorName);
        addGroupNode(nodeModelList);
        for (Node_Model nodeModel : nodeModelList) {
            GoJsNodeEntity asyncFlowNodeDataArray = new GoJsNodeEntity();

            asyncFlowNodeDataArray.setKey(nodeModel.getName());
            asyncFlowNodeDataArray.setParent("");
            asyncFlowNodeDataArray.setDescription("文件：" + nodeModel.getName());
            asyncFlowNodeDataArray.setName(nodeModel.getDes());
            //asyncFlowNodeDataArray.setSource("");
            if (nodeModel.getExecuteEnum().equals(ExecuteEnum.Validator)) {
                asyncFlowNodeDataArray.setFill("#468B58");
            }
            if (nodeModel.getExecuteEnum().equals(ExecuteEnum.GetData)) {
                asyncFlowNodeDataArray.setFill("#D1C667");
            }
            if (nodeModel.getExecuteEnum().equals(ExecuteEnum.Operator)) {
                asyncFlowNodeDataArray.setFill("#AED54C");
            }
            if (nodeModel.getExecuteEnum().equals(ExecuteEnum.Save)) {
                asyncFlowNodeDataArray.setFill("#499C9F");
            }
            if (nodeModel.getExecuteEnum().equals(ExecuteEnum.Sync)) {
                asyncFlowNodeDataArray.setFill("#FBD0E5");
            }
            if (nodeModel.getExecuteEnum().equals(ExecuteEnum.Async)) {
                asyncFlowNodeDataArray.setFill("#EEA157");
            }
            if (nodeModel.isGroupNode()) {
                asyncFlowNodeDataArray.setFill("#9EA0A1");
            }
            asyncFlowNodeDataArrays.add(asyncFlowNodeDataArray);
        }

        return asyncFlowNodeDataArrays;
    }

    /**
     * 加载连线集合
     *
     * @param managerName  模块名称
     * @param operatorName 操作节点名称
     * @return 连线集合
     */
    public static LinkedList<GoJsLinkDataEntity> loadNodeLinkArray(String managerName, String operatorName) {

        List<Node_Model> nodeModelList = getManagerNodeInfo(managerName, operatorName);
        addGroupNode(nodeModelList);
        LinkedList<GoJsLinkDataEntity> linkDataArray = new LinkedList<>();
        for (Node_Model nodeModel : nodeModelList) {
            getToLinkDataArray(nodeModel, nodeModelList, linkDataArray);
        }
        return linkDataArray;

    }

    //endregion

    /**
     * 获取节点之间的连线
     *
     * @param thisNodeModel    当前节点
     * @param nodeModelList    节点结合
     * @param allLinkDataArray 连线集合
     */
    private static void getToLinkDataArray(Node_Model thisNodeModel, List<Node_Model> nodeModelList, List<GoJsLinkDataEntity> allLinkDataArray) {

        if (thisNodeModel == null) {
            return;
        }
        int allCount = nodeModelList.size();
        int thisIndex = nodeModelList.indexOf(thisNodeModel);
        boolean nextHasAsync = false;
        for (int i = thisIndex + 1; i < allCount; i++) {
            GoJsLinkDataEntity linkData = new GoJsLinkDataEntity();
            Node_Model nodeModel = nodeModelList.get(i);
            linkData.setFrom(thisNodeModel.getName());


            if (thisNodeModel.isAsync()) {
                if (!nodeModel.isAsync()) {
                    linkData.setTo(nodeModel.getName());
                    allLinkDataArray.add(linkData);
                    break;
                } else {
                    if (thisNodeModel.getExecuteEnum().getCode() != nodeModel.getExecuteEnum().getCode()) {
                        linkData.setTo(nodeModel.getName());
                        allLinkDataArray.add(linkData);
                    }
                }
            } else {
                if (!nodeModel.isAsync()) {
                    if (nextHasAsync) {
                        break;
                    }
                    linkData.setTo(nodeModel.getName());
                    allLinkDataArray.add(linkData);
                    break;
                } else {
                    nextHasAsync = true;
                    linkData.setTo(nodeModel.getName());
                    allLinkDataArray.add(linkData);
                }
            }
        }
    }


    /**
     * 加载异步流管理器节点信息
     *
     * @param managerName  管理器名称
     * @param operatorName 操作类型
     */
    private static List<Node_Model> getManagerNodeInfo(String managerName, String operatorName) {
        List<Node_Model> nodeModelList = new ArrayList<>();
        //加载管理器下所有节点
        VelocityRequest velocityRequest = AsyncFlowVelocity.loadManagerNode(managerName);
        List<VelocityModel.AsyncFlowOperatorEnumInfo> asyncFlowOperatorEnumInfoList = velocityRequest.getAsyncFlowOperatorEnumInfoList();
        List<VelocityModel.AsyncFlowNodeInfo> asyncFlowNodeInfoList = velocityRequest.getAsyncFlowNodeInfoList();
        for (VelocityModel.AsyncFlowNodeInfo asyncFlowNodeInfo : asyncFlowNodeInfoList) {

            //非空标识是特殊节点（不是公共节点），特定节点需要判断是否是当前操作枚举
            //不是当前操作枚举的节点直接跳过
            if (StringUtils.isNotBlank(asyncFlowNodeInfo.getOperatorName()) && !asyncFlowNodeInfo.getOperatorName().equals(operatorName)) {
                continue;
            }
            Node_Model node_Model = new Node_Model();
            node_Model.setName(asyncFlowNodeInfo.getAsyncFlowNodeFileName());
            node_Model.setDes(asyncFlowNodeInfo.getAsyncFlowNodeDes() + "【" + asyncFlowNodeInfo.isAsync() + "】");
            node_Model.setExecuteEnum(asyncFlowNodeInfo.getExecuteEnum());
            node_Model.setFilePath(asyncFlowNodeInfo.getAsyncFlowNodeFilePath());
            node_Model.setNode_PackagePath(asyncFlowNodeInfo.getAsyncFlowNodePackagePath());

            if (asyncFlowNodeInfo.getNodeTypeEnum().equals(NodeTypeEnum.OldSpecialNode) || asyncFlowNodeInfo.getNodeTypeEnum().equals(NodeTypeEnum.NewSpecialNode)) {
                node_Model.setSpecialNode(true);
            }
            if (asyncFlowNodeInfo.getNodeTypeEnum().equals(NodeTypeEnum.NewPubNode) || asyncFlowNodeInfo.getNodeTypeEnum().equals(NodeTypeEnum.NewSpecialNode)) {
                node_Model.setAddNode(true);
            }
            // node_Model.setGroupNode();
            node_Model.setExecuteEnum(asyncFlowNodeInfo.getExecuteEnum());
            node_Model.setAsync(asyncFlowNodeInfo.isAsync());
            nodeModelList.add(node_Model);
        }
        return nodeModelList;
    }

    /**
     * 添加分组节点
     *
     * @param nodeModelList 原始节点列表
     */
    private static void addGroupNode(List<Node_Model> nodeModelList) {
        Node_Model start_Request_GroupNode = new Node_Model();
        start_Request_GroupNode.setName("Start_Request");
        start_Request_GroupNode.setDes("请求");
        start_Request_GroupNode.setGroupNode(true);
        start_Request_GroupNode.setExecuteEnum(ExecuteEnum.Manager);
        nodeModelList.add(0, start_Request_GroupNode);


        ExecuteEnum thisExecuteEnum = null;
        ExecuteEnum beforExecuteEnum = null;
        for (int i = 0; i < nodeModelList.size(); i++) {

            Node_Model nodeModel = nodeModelList.get(i);
            thisExecuteEnum = nodeModel.getExecuteEnum();
            int thisIndex = nodeModelList.indexOf(nodeModel);
            if (thisExecuteEnum != beforExecuteEnum && thisExecuteEnum != ExecuteEnum.Save && !nodeModel.getName().equals("Start_Request")) {
                Node_Model groupNode = new Node_Model();
                groupNode.setName("start_" + thisExecuteEnum.getName());
                groupNode.setDes("开始" + thisExecuteEnum.getMsg());
                groupNode.setGroupNode(true);
                groupNode.setExecuteEnum(thisExecuteEnum);
                groupNode.setAsync(false);
                nodeModelList.add(thisIndex, groupNode);
                i = i + 1;
            }
            beforExecuteEnum = thisExecuteEnum;
        }
        Node_Model end_Response_GroupNode = new Node_Model();
        end_Response_GroupNode.setName("End_Response");
        end_Response_GroupNode.setDes("返回");
        end_Response_GroupNode.setExecuteEnum(ExecuteEnum.Manager);
        end_Response_GroupNode.setGroupNode(true);
        nodeModelList.add(nodeModelList.size(), end_Response_GroupNode);


    }


    @SneakyThrows
    public static String addModuleInfo(String name, String des) {
        String result = "新增成功";
        Yaml yaml = new Yaml();
        InputStream resourceAsStream = AsyncFlowVelocity.class.getClassLoader().getResourceAsStream("asyncflow.yml");
        Map obj = yaml.load(resourceAsStream);
        String basePackagePath = (String) obj.get("AsyncFlowDomainPackagePath");
        String packagePath = basePackagePath + ".operatorenum.ModuleInfoEnum";


        Class<?> clazz = Class.forName(packagePath);

        String oldOperatorEnumFilePath;
        oldOperatorEnumFilePath = Objects.requireNonNull(clazz.getResource("")).getPath().replace("target/classes", "src/main/java") + clazz.getSimpleName() + ".java";
        Path path = Paths.get(oldOperatorEnumFilePath);
        File file = path.toFile();
        //解析java文件生成AST
        CompilationUnit cu = StaticJavaParser.parse(file);

        EnumDeclaration enumDeclaration = cu.findAll(EnumDeclaration.class).get(0);
        List<EnumConstantDeclaration> existingEnumConstants = enumDeclaration.getEntries();
        if (existingEnumConstants.stream().anyMatch(c -> c.getName().equals(name))) {
            return "失败！存在同样的模块名称";
        }
        // 添加新的枚举值
        String newEnumValue = String.format("%s(%s,\"%s\")", name, existingEnumConstants.size() + 1, des);

        enumDeclaration.addEnumConstant(String.valueOf(new EnumConstantDeclaration(newEnumValue)));

        // 将修改后的AST重新格式化为源代码
        String formattedCode = cu.toString();
        // 将字符串写回到文件
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(formattedCode);
        }
        return result;
    }

    @SneakyThrows
    public static String editManagerModuleInfo(String managerName, String managerModuleName, String managerModuleNameDes) {

        LinkedList<VelocityModel.AsyncFlowNodeInfo> allManagers = AsyncFlowVelocity.loadNodeAndManagerV2();
        VelocityModel.AsyncFlowNodeInfo manager = allManagers.stream().filter(c -> c.getAsyncFlowNodeFileName().equals(managerName) && c.getExecuteEnum().equals(ExecuteEnum.Manager)).findFirst().orElse(null);
        String result = "修改成功";
        assert manager != null;
        Path path = Paths.get(manager.getAsyncFlowNodeFilePath());
        File file = path.toFile();
        //解析java文件生成AST
        CompilationUnit cu = StaticJavaParser.parse(file);

        Yaml yaml = new Yaml();
        InputStream resourceAsStream = AsyncFlowVelocity.class.getClassLoader().getResourceAsStream("asyncflow.yml");
        Map obj = yaml.load(resourceAsStream);
        String basePackagePath = (String) obj.get("AsyncFlowDomainPackagePath");
//        String importPath = basePackagePath + ".operatorenum";
        // 查找需要添加import的类
//        ClassOrInterfaceDeclaration targetClass = cu.findFirst(ClassOrInterfaceDeclaration.class, c ->
//                c.getNameAsString().equals("ModuleInfoEnum")
//        ).orElse(null);
//        if (cu.getImports().stream().noneMatch(c -> c.getName().toString().contains("ModuleInfoEnum"))) {
//            // 创建新的import声明
//            ImportDeclaration newImport = new ImportDeclaration(importPath, true, false); // 例如导入java.util.List
//
//            // 在类声明的顶部添加新的import
//            cu.getImports().add(newImport);
//        }
        String packagePath = basePackagePath + ".operatorenum.ModuleInfoEnum";
        Class<?> clazz = Class.forName(packagePath);
        LinkedList<VelocityModel.AsyncFlowOperatorEnumInfo> allEnumInfo = AsyncFlowVelocity.getEnumInfo(null, (Class<Enum<?>>) clazz);
        VelocityModel.AsyncFlowOperatorEnumInfo enumInfo = allEnumInfo.stream().filter(c -> c.getName().equals(managerModuleName)).findFirst().orElse(null);
        String managerModuleDes = "";
        if (enumInfo == null) {
            managerModuleDes = managerModuleName + "[" + managerModuleNameDes + "]";
        } else {
            managerModuleDes = enumInfo.getMsg() + "[" + enumInfo.getName() + "]";
        }
        List<AnnotationExpr> annotationNodes = cu.findAll(AnnotationExpr.class);
        for (AnnotationExpr annotation : annotationNodes) {

            if ("FlowInfo".equals(annotation.getName().toString())) {
                // 处理 @FlowInfo 注解的逻辑
                String s = annotation.getName().toString();
                //TODO 修改@FlowInfo 注解中的参数值
                if (annotation instanceof NormalAnnotationExpr) {
                    NormalAnnotationExpr normalAnnotationExpr = (NormalAnnotationExpr) annotation;
                    if (normalAnnotationExpr.getPairs().stream().anyMatch(c -> c.getName().toString().equals("parentModuleName"))) {
                        for (MemberValuePair pair : normalAnnotationExpr.getPairs()) {
                            if ("parentModuleName".equals(pair.getName().toString())) {
                                pair.setValue(new StringLiteralExpr(managerModuleDes));
                                break;
                            }
                        }
                    } else {
                        MemberValuePair newMemberValuePair = new MemberValuePair();
                        newMemberValuePair.setName("parentModuleName");
                        newMemberValuePair.setValue(new StringLiteralExpr(managerModuleDes));
                        normalAnnotationExpr.getPairs().add(newMemberValuePair);
                    }

                }
            }
        }

        // 将修改后的AST转换回字符串
        String modifiedCode = cu.toString();

        // 将字符串写回到文件
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(modifiedCode);
        }
        return result;
    }
}
